/**
 * 
 */
package org.mhz.ootw.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.mhz.ootw.annotation.LogTimeTaken;
import org.mhz.ootw.dataaccess.RepositoryContentsDAO;
import org.mhz.ootw.entity.ReadableContent;
import org.mhz.ootw.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.googlecode.ehcache.annotations.Cacheable;

/**
 * @author Mahan
 *
 * Repository contents service
 */
@Service(Constants.REPOSITORY_CONTENTS_SERVICE)
public class RepositoryContentsService implements ContentsService
{
    private static final Logger LOGGER = LoggerFactory.getLogger(RepositoryContentsService.class);
    
    @Resource(name = Constants.REPOSITORY_CONTENTS_DAO)
    private RepositoryContentsDAO mRepositoryContentsDAO;
    
    /* (non-Javadoc)
     * @see org.mhz.ootw.service.ContentsService#getContents()
     */
    @Override
    @Cacheable(cacheName = Constants.OCEAN_CACHE)
    @LogTimeTaken    
    public String getContents(final String aNodeId)
    {
        final List<ReadableContent> readableContents = mRepositoryContentsDAO.getAll(aNodeId);        
        final String contents = makeReadable(readableContents);

        // LOGGER.trace(contents);
        
        return contents;
    }

    /**
     * @param aReadableContents - The readable contents
     * @return The readable contents as a string
     */
    private String makeReadable(final List<ReadableContent> aReadableContents)
    {
        final StringBuilder contentsBuilder = new StringBuilder();
        
        if (CollectionUtils.isNotEmpty(aReadableContents))
        {
            for (ReadableContent readableContent : aReadableContents)
            {
                contentsBuilder.append("<a name=\"");
                contentsBuilder.append(readableContent.getId());
                contentsBuilder.append("\"></a>");
                contentsBuilder.append("<div id=\"");
                contentsBuilder.append(readableContent.getId());   
                contentsBuilder.append("\">");
                contentsBuilder.append(readableContent.getContent());
                contentsBuilder.append("</div>");
                contentsBuilder.append("<p/>");
            }
        }
        else
        {
            contentsBuilder.append("Could not find or load contents");
        }
        
        return contentsBuilder.toString();
    }
}
